package queue.impl;

import queue.Queue;

import java.util.NoSuchElementException;


class Node<E>{
    E val;
    Node next;

    public Node(E val) {
        this.val = val;
    }
}

public class LinkedQueue<E> implements Queue<E> {
    //当前队列的元素个数
    private int size;
    //头节点
    private Node<E> head;
    //队尾元素
    private Node<E> tail;

    /**
     * 添加元素
     * @param val
     */
    @Override
    public void offer(E val) {
       Node<E> node=new Node<>(val);
       if (head==null){
           head=tail=node;
       }else {
           tail.next=node;
           tail=node;
       }
       size++;
    }

    /**
     * 弹出队首元素
     * @return
     */
    @Override
    public E poll() {
        if (isEmptty()){
            throw new NoSuchElementException("Queue is Empty!cannot is poll!");
        }
        E val= head.val;
        Node<E> node=head;
        head=head.next;
        node.next=node=null;
        size--;
        return val;
    }

    /**
     * 查看队首元素
     * @return
     */
    @Override
    public E peek() {
        if (isEmptty()){
            throw new NoSuchElementException("Queue is Empty!cannot is peek!");
        }
        return head.val;
    }

    /**
     * 判断队列是否为空
     * @return
     */
    @Override
    public boolean isEmptty() {
        return size==0;
    }

    @Override
    public String toString() {
        StringBuilder sb=new StringBuilder();
        sb.append("front [");
        for (Node x=head;x!=null;x=x.next) {
            sb.append(x.val);
            if (x.next!=null){
                sb.append(", ");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }
}
